package com.mdlib.helper.sqlite;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.mdlib.helper.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者：HQY on 16/12/21 10:53
 * 邮箱：hqy_xz@126.com
 */

public class KeySQLiteOpenHelper extends SQLiteOpenHelper {
    private static String name = "KEY.db";
    private static Integer version = 1;

    public KeySQLiteOpenHelper(Context context) {
        super(context, name, null, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String keyWrods = "create table keywords(id integer primary key autoincrement,content varchar(255))";
        db.execSQL(keyWrods);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {
        db.execSQL("DROP TABLE IF EXISTS keywords");
        onCreate(db);
    }


    public void saveKey(String keywords) {

        if (queryList().size() <= 30) {
            SQLiteDatabase db = getWritableDatabase();
            String saveKey = "insert into keywords(content) values(?)";
            db.execSQL(saveKey, new Object[]{keywords});
        } else {
            ToastUtil.showToast("已经放不下了,请先删除再添加!");
        }
    }

    public void deleteKey(String keywords) {
        SQLiteDatabase db = getWritableDatabase();
        String deleteKey = "delete from keywords where content=?";
        db.execSQL(deleteKey, new Object[]{keywords});

    }

    public List<String> queryList() {
        List<String> content = new ArrayList<>();
        SQLiteDatabase db = getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from keywords", null);
        while (cursor.moveToNext()) {
            content.add(cursor.getString(cursor.getColumnIndex("content")));
        }
        return content;
    }
}
